package com.yingxin.yxerp.module.permission.controller;

import cn.hutool.core.bean.BeanUtil;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.yingxin.yx.framework.commons.constant.CommonConst;
import com.yingxin.yx.framework.commons.helper.ListHelper;
import com.yingxin.yx.framework.user.dto.PermissionDto;
import com.yingxin.yxerp.module.permission.entity.Permission;
import com.yingxin.yxerp.module.permission.entity.Role;
import com.yingxin.yxerp.module.permission.mapper.PermissionMapper;
import com.yingxin.yxerp.module.permission.mapper.RoleMapper;
import com.yingxin.yxerp.module.permission.service.IPermissionService;
import com.yingxin.yxerp.module.permission.service.IRoleService;
import com.yingxin.yxerp.module.permission.vo.req.RoleCreateVo;
import com.yingxin.yxerp.module.permission.vo.req.RoleQueryVo;
import com.yingxin.yxerp.module.permission.vo.req.RoleUpdateVo;
import com.yingxin.yxerp.module.permission.vo.resp.RoleRespVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**

 * 角色 前端控制器
 * @author fanchao
 * @since 2021-05-13
 */

@ApiSort(30)
@RestController
@RequestMapping("/permission/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    @SuppressWarnings("all")
    private RoleMapper roleMapper;

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    @SuppressWarnings("all")
    private PermissionMapper permissionMapper;

    /*
    @PreAuthorize("hasAuthority('sys:role:view')")
    @ApiOperation(value = "查询列表（分页）")
    @PostMapping("/page")
    public PageOut<RoleRespVo> page(@RequestBody RoleQueryVo queryVo) {
        IPage<RoleRespVo> page = roleMapper.pageVo(PageHelper.in(queryVo), queryVo);
        return PageHelper.out(page);
    }
     */

    @PreAuthorize("hasAuthority('sys:role:view')")
    @ApiOperation(value = "查询列表（全部）")
    @PostMapping("/list")
    public List<RoleRespVo> list(@RequestBody RoleQueryVo queryVo) {
        return roleMapper.listVo(queryVo);
    }

    @PreAuthorize("hasAuthority('sys:role:view')")
    @ApiOperation(value = "查询可用角色列表（全部）")
    @PostMapping("/list/enable")
    public List<RoleRespVo> listEnable(@RequestBody RoleQueryVo queryVo) {
        queryVo.setStatus(CommonConst.TRUE);
        return roleMapper.listVo(queryVo);
    }

    @ApiOperation(value = "根据id查询")
    @GetMapping("/{id}")
    public RoleRespVo get(@PathVariable("id") String id) {
        RoleRespVo role = roleMapper.getVo(id);
        List<PermissionDto> rolePermissions = permissionMapper.listDtoByRoleId(id);
        Map<String, PermissionDto> rolePermissionsMap = ListHelper.toMap(PermissionDto::getId, rolePermissions);
        // 叶子节点权限
        //List<PermissionDto> leafPermissions = new ArrayList<>();
        //for (PermissionDto permission : rolePermissions) {
        //    if (PermissionConst.Type.P.equals(permission.getType())) {
        //       leafPermissions.add(permission);
        //   }
        // }
        // rolePermissions 包含父级，前端要求的数据是只有叶子节点的数据，叶子节点可能是菜单也可能是权限
        List<Permission> allPermissions = permissionService.list();
        for (Permission permission : allPermissions) {
            rolePermissionsMap.remove(permission.getParentId());
        }
        rolePermissions = new ArrayList<>(rolePermissionsMap.values());
        role.setPermissions(rolePermissions);
        role.setPermissionIds(ListHelper.toList(PermissionDto::getId, rolePermissions));
        return role;
    }

    @PreAuthorize("hasAuthority('sys:role:create')")
    @ApiOperation(value = "新增")
    @PostMapping
    public String create(@RequestBody @Valid RoleCreateVo createVo) {
        // 角色
        Role role = new Role();
        BeanUtil.copyProperties(createVo, role);
        roleService.create(role, createVo.getPermissionIds());
        return role.getId();
    }

    @PreAuthorize("hasAuthority('sys:role:update')")
    @ApiOperation(value = "修改")
    @PutMapping
    public String update(@RequestBody @Valid RoleUpdateVo updateVo) {
        // 角色
        Role role = new Role();
        BeanUtil.copyProperties(updateVo, role);
        roleService.update(role, updateVo.getPermissionIds());
        return role.getId();
    }

    @PreAuthorize("hasAuthority('sys:role:delete')")
    @ApiOperation(value = "删除")
    @DeleteMapping("/{id}")
    public void delete(@PathVariable("id") String id) {
        Role role = roleService.getById(id);
        roleService.delete(role);
    }


    @PreAuthorize("hasAuthority('sys:role:enable')")
    @ApiOperation("启用")
    @PostMapping("/enable/{id}")
    public void enable(@PathVariable("id") String id) {
        Role role = roleService.getById(id);
        roleService.enable(role);
    }

    @PreAuthorize("hasAuthority('sys:role:disable')")
    @ApiOperation("禁用")
    @PostMapping("/disable/{id}")
    public void disable(@PathVariable("id") String id) {
        Role role = roleService.getById(id);
        roleService.disable(role);
    }

}
